from flask import jsonify, request, current_app, blueprints
from application.utils.UrlFetcher import UrlFetcher
from application.utils.TextClassifier import TextClassifier
from application.utils.QianFan import qf
import pytesseract
from PIL import Image
import io

api_bp = blueprints.Blueprint('api', __name__)
fetcher = UrlFetcher()
textClassifier = TextClassifier(vocab_path='./application/src/dict.txt',
                                model_path='./application/src/model_final.pdparams')


@api_bp.route('/v1/process_text_normal', methods=['POST'])
def process_text_normal():
    text = request.json.get('text')
    if not text:
        return jsonify({'error': 'text is required'}), 400
    try:
        result, conf = textClassifier.predict(text)
        return jsonify({'result': str(result), 'confidence': str(conf)})
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@api_bp.route('/v1/process_text_pro', methods=['POST'])
def process_text_pro():
    text = request.json.get('text')
    if not text:
        return jsonify({'error': 'text is required'}), 400
    try:
        result, conf = textClassifier.predict(text)
        if result == "不是谣言":
            return jsonify({'result': str(result), 'confidence': str(conf)})
        elif result == "谣言":
            reason = qf(text + "这段新闻被判定为谣言的原因是？")
            return jsonify({'result': str(result), 'confidence': str(conf), 'reason': reason})
        else:
            # TODO 尚无定论处理逻辑
            return jsonify({'result': str(result), 'confidence': str(conf)})
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@api_bp.route('/v1/fetch_url', methods=['POST'])
def fetch_url():
    url = request.json.get('url')
    if not url:
        return jsonify({'error': 'url is required'}), 400
    try:
        article = fetcher.fetch(url)
        return jsonify(article)
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@api_bp.route('v1/ocr', methods=['POST'])
def ocr():
    pytesseract.pytesseract.tesseract_cmd = current_app.config['TESSERACT_CMD']
    if 'image' not in request.files:
        return jsonify({'error': 'image is required'}), 400

    image_file = request.files['image']

    if not image_file.filename:
        return jsonify({'error': 'file name is required'}), 400

    allowed_extensions = current_app.config['ALLOWED_EXTENSIONS']
    if not ('.' in image_file.filename and
            image_file.filename.rsplit('.', 1)[1].lower() in allowed_extensions):
        return jsonify({'error': 'invalid image format'}), 400

    try:
        image = Image.open(io.BytesIO(image_file.read()))
        text = pytesseract.image_to_string(image, lang='chi_sim')
        return jsonify({'text': text.strip()})

    except pytesseract.TesseractNotFoundError:
        return jsonify({'error': 'tesseract not found'}), 500
    except Exception as e:
        return jsonify({'error': str(e)}), 500
